# -*- coding: iso-8859-2 -*-

import email
import os
import traceback
import re
import string
import quopri
import base64
import email.utils

from authorshipanalyzer.message import Message
from authorshipanalyzer.message.parser import Parser
from authorshipanalyzer.logger import GlobalLogger

logger = GlobalLogger.getLogger()

class ParserCurrent(Parser):
    '''
    Parser for info1 messages in the new type
    compliant to RFC 2822
    '''
    
    def retrieveMessages(self, filename):
        '''
        Function retrieving messages from a given filename
        @param filename: path to the file with messages 
        '''
        logger.info("Retrieving: " + filename)        
       
        inMessage = False
       
        try:
            file = open(filename, "r")

            first = True
            emailContent = ""
            for line in file.readlines():
                if re.match("^From ", line):
                    if first == True:
                        first = False 
                    else:  
                        self._createAndAppendMessage(emailContent, filename)
                        emailContent = ""
                        
                emailContent += line      
            self._createAndAppendMessage(emailContent, filename)
        except IOError:
            #file existance is checked level above
            print_exc()
        finally:
            file.close()
    

    def _createAndAppendMessage(self, emailContent, filename):
        '''
        Create message from retrieved paragraph
        and append to the message list
        @param emailContent
        @param filename
        '''
        msg = email.message_from_string(emailContent)
        message = self._createMessage(msg)
        if message.getDate() == "":
            self._setApproximateDate(message, filename)
        self._appendToMessages(message)
    
    def _parseAuthorLine(self, line):
        '''
        @return: author name
        '''
        result = ""
        for word in str(line).split():
            if re.match(".*@.*", word) == None:
                result += word + " "
            
        return result.strip()

    def _parseSubjectLine(self, line):
        '''
        @return: subject of the message
        '''
        if line == None:
            return ""
        
        line = line[8:].strip()
            
        if re.match("^\[info1\]", line) != None:
            line = line[7:].strip()
            
        while (re.match("^(Re:|Odp:)", line, re.IGNORECASE) != None):
            if re.match("^Re:", line, re.IGNORECASE):
                line = line[3:].strip()
            else:
                line = line[4:].strip()
                    
        return line.strip()
   
    def _retrieveEmail(self, msg):
        '''
        @return: email address of the writer
        '''
        result = msg.get("X-original-sender")
        if result != None:
            return result
        
        result = msg.get("From")
        for word in str(result).split():
            if re.match(".*@.*", word) != None:
                return word
            
        return ""
   
    def _createMessage(self, msg):     
        '''
        Create message from a paragraph with single message
        '''   
        message = Message()
        message.setAuthor(self._parseAuthorLine(msg.get("From")))
        message.setAddress(self._retrieveEmail(msg))
        message.setSubject(self._parseSubjectLine(msg.get("Subject")))
        message.setDate(self._parseDateLine(msg.get("Date")))
        message.setText(self._retrieveText(msg))
        
        return message           
        
    def _parseDateLine(self, dateLine):
        return email.utils.parsedate(dateLine)        
        
    def _retrieveText(self, msg):
        '''
        Recursively retrieve text from message. It is done
        for single as well as for multipart messages where 
        texts from messages are joined into one message.
        '''
        if (not msg.is_multipart()):
            return msg.get_payload()
        
        text = ""
        for index in range(0, len(msg.get_payload())):
            text += self._retrieveText(msg.get_payload(index))
        return text
   
if __name__ == "__main__":
    from authorshipanalyzer.file import Path
    
    parser = ParserCurrent()
    parser.retrieveMessages(Path.getMainDir() + os.sep + "info1" + os.sep + "info1.2008-03")
    messages = parser.getMessageList()
    print len(messages)
    
    for message in messages:
        message.printInfo()